package org.bb.es.heighlevel.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class EsHighLevelAop implements EsRestHighLevelClientConfig {
    @Pointcut("@annotation(org.bb.es.heighlevel.config.EsHighLevelClient)")
    public void pointcut() {
    }

    @Around(value = "pointcut()")
    public Object invoke(ProceedingJoinPoint invocation) throws Throwable {
        if (TH_CLIENT.get() == null) {
            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(
                            new HttpHost("192.168.61.3", 9200, "http"),
                            new HttpHost("192.168.61.4", 9200, "http"),
                            new HttpHost("192.168.61.5", 9200, "http"),
                            new HttpHost("192.168.61.6", 9200, "http"),
                            new HttpHost("192.168.61.7", 9200, "http")
                    )
            );
            TH_CLIENT.set(client);
        }
        try {
            Object result = invocation.proceed();
            return result;
        } finally {
            RestHighLevelClient client = TH_CLIENT.get();
            if (client != null) {
                TH_CLIENT.remove();
                client.close();
            }
        }
    }
}
